﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.ComponentModel;

using System.Data.Linq;
using System.Data.Linq.Mapping;

using System.Linq.Expressions;
using System.Reflection;
public struct ths
{
    public string Name1 { get; set; }

    public int DepartmentID { get; set; }

}

public partial class UserControls_admintree : System.Web.UI.UserControl
{
    private static DataClassesDataContext da = new DataClassesDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        gte();
    }
    private static string BuildAbsolute(string relativeUri)
    {
        // get current uri
        Uri uri = HttpContext.Current.Request.Url;
        // build absolute path
        string app = HttpContext.Current.Request.ApplicationPath;
        if (!app.EndsWith("/")) app += "/";
        relativeUri = relativeUri.TrimStart('/');
        // return the absolute path
        return HttpUtility.UrlPathEncode(
          String.Format("http://{0}:{1}{2}{3}",
          uri.Host, uri.Port, app, relativeUri));
    }
    protected void gte()
    {
        ISingleResult<getree1Result> thetre1 = da.getree1();
        List<getree1Result> thetre = thetre1.ToList();
        List<ths> ctrs = thetre.Select(h => new ths() { Name1 = h.Name1, DepartmentID = h.DepartmentID }).Distinct().ToList();
        foreach (ths ctr in ctrs)
        {
            TreeNode node1 = new TreeNode();
            node1.Expanded = true;
            node1.Value = ctr.DepartmentID.ToString();
            node1.Text = ctr.Name1;
            node1.NavigateUrl = BuildAbsolute(String.Format("AdminCategories.aspx?DepartmentID={0}", ctr.DepartmentID.ToString()));
            foreach (getree1Result ctg in thetre.Where(h => h.DepartmentID == ctr.DepartmentID).ToList())
            {
                TreeNode node2 = new TreeNode();
                node2.Expanded = true;
                node2.Value = ctg.CategoryID.ToString();
                node2.Text = ctg.Name;
                node2.NavigateUrl =BuildAbsolute(String.Format("AdminProducts.aspx?DepartmentID={0}&CategoryID={1}" , ctr.DepartmentID.ToString() , ctg.CategoryID.ToString()));
                node1.ChildNodes.Add(node2);
            }
            this.TreeView1.Nodes.Add(node1);
            //  TextBox1.Text = thetre.GroupBy(h => h.DepartmentID).ToList().Count().ToString();
        }
    }
}